package com.zhijian.warehouse.manage.util;

import com.zhijian.util.BeanUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;

public class SnowFlake {
    private static final Logger log = LoggerFactory.getLogger(SnowFlake.class);

    private static final long START_TIME = 1609434800000L;
    private static final long BIT_WORK = 5L;
    private static final long BIT_DATACENTER = 5L;
    private static final long BIT_SEQUENCE = 12L;
    private long workerMaxId;
    private long datacenterMaxId;
    private long sequenceMax;
    private long workerIdLeft;
    private long datacenterIdLeft;
    private long timestampLeftLeft;
    private long workerId;
    private long datacenterId;
    private long lastTime;
    private long sequence;

    public SnowFlake() {
        this(5L, 5L, 12L);
    }

    public SnowFlake(long datacenterId, long workerId) {
        this(datacenterId, workerId, 5L, 5L, 12L);
    }

    public SnowFlake(long datacenterIdBit, long workerIdBit, long sequenceBit) {
        this.lastTime = -1L;
        this.sequence = 0L;
        this.datacenterMaxId = ~(-1L << (int)datacenterIdBit);
        this.workerMaxId = ~(-1L << (int)workerIdBit);
        this.sequenceMax = ~(-1L << (int)sequenceBit);
        this.workerIdLeft = sequenceBit;
        this.datacenterIdLeft = sequenceBit + workerIdBit;
        this.timestampLeftLeft = sequenceBit + workerIdBit + datacenterIdBit;
        this.datacenterId = this.getDatacenterId(this.datacenterMaxId);
        this.workerId = this.getWorkerId(this.datacenterId, this.workerMaxId);
        if (this.workerId <= this.workerMaxId && this.workerId >= 0L) {
            if (this.datacenterId > this.datacenterMaxId || this.datacenterId < 0L) {
                throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", this.datacenterMaxId));
            }
        } else {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", this.workerMaxId));
        }
    }

    public SnowFlake(long datacenterId, long workerId, long datacenterIdBit, long workerIdBit, long sequenceBit) {
        this.lastTime = -1L;
        this.sequence = 0L;
        this.datacenterMaxId = ~(-1L << (int)datacenterIdBit);
        this.workerMaxId = ~(-1L << (int)workerIdBit);
        this.sequenceMax = ~(-1L << (int)sequenceBit);
        this.workerIdLeft = sequenceBit;
        this.datacenterIdLeft = sequenceBit + workerIdBit;
        this.timestampLeftLeft = sequenceBit + workerIdBit + datacenterIdBit;
        this.workerId = workerId;
        this.datacenterId = datacenterId;
        if (workerId <= this.workerMaxId && workerId >= 0L) {
            if (datacenterId > this.datacenterMaxId || datacenterId < 0L) {
                throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", this.datacenterMaxId));
            }
        } else {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", this.workerMaxId));
        }
    }

    public synchronized long nextId() {
        long curTime = this.time();
        if (curTime < this.lastTime) {
            throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", this.lastTime - curTime));
        } else {
            if (curTime == this.lastTime) {
                this.sequence = this.sequence + 1L & this.sequenceMax;
                if (this.sequence == 0L) {
                    curTime = this.nextMillis(this.lastTime);
                }
            } else {
                this.sequence = 0L;
            }

            this.lastTime = curTime;
            return curTime - 1609434800000L << (int)this.timestampLeftLeft | this.datacenterId << (int)this.datacenterIdLeft | this.workerId << (int)this.workerIdLeft | this.sequence;
        }
    }

    private long nextMillis(long lastTime) {
        long cutTime;
        for(cutTime = this.time(); cutTime <= lastTime; cutTime = this.time()) {
        }

        return cutTime;
    }

    public long time() {
        return System.currentTimeMillis();
    }

    protected long getDatacenterId(long maxDatacenterId) {
        long id = 0L;

        try {
            InetAddress ip = InetAddress.getLocalHost();
            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
            if (network == null) {
                id = 1L;
            } else {
                byte[] mac = network.getHardwareAddress();
                id = (255L & (long)mac[mac.length - 1] | 65280L & (long)mac[mac.length - 2] << 8) >> 6;
                id %= maxDatacenterId + 1L;
            }
        } catch (Exception var8) {
            Exception ex = var8;
            log.error("getDatacenterId error", ex);
        }

        return id;
    }

    protected long getWorkerId(long datacenterId, long maxWorkerId) {
        StringBuilder mpid = new StringBuilder();
        mpid.append(datacenterId);
        String name = ManagementFactory.getRuntimeMXBean().getName();
        if (!BeanUtil.isEmpty(name)) {
            mpid.append(name.split("@")[0]);
        }

        return (long)(mpid.toString().hashCode() & '\uffff') % (maxWorkerId + 1L);
    }
}
